import 'package:fish_redux/fish_redux.dart';
import '../../../app_files.dart';
import 'action.dart';
import 'state.dart';

Effect<EngineerListViewState> buildEffect() {
  return combineEffects(<Object, Effect<EngineerListViewState>>{
    EngineerListViewAction.action: _onAction,
    Lifecycle.initState: _initState,
    EngineerListViewAction.onLoad: _onLoad,
    EngineerListViewAction.onTapSort: _onTapSort,
  });
}

void _onAction(Action action, Context<EngineerListViewState> ctx) {}

void _initState(Action action, Context<EngineerListViewState> ctx) {
  _sendRequest(ctx, 1);
}

void _onLoad(Action action, Context<EngineerListViewState> ctx) async {
  await _sendRequest(ctx, action.payload);
}

void _onTapSort(Action action, Context<EngineerListViewState> ctx) async {
  ctx.state.currentSortIndex = action.payload;
  ctx.dispatch(EngineerListViewActionCreator.setSort(action.payload));
  _sendRequest(ctx, 1);
}

_sendRequest(Context<EngineerListViewState> ctx, int page) async {
  if (ctx.state.type == 5) {
    int orderState = ctx.state.currentSortIndex + 1;
    if (ctx.state.currentSortIndex == 2) orderState = 4;
    if (ctx.state.currentSortIndex == 3) orderState = 5;
    ResultData res = await CommonNetWork.engineerOrderList(
      workId: GlobalStore.store.getState().userInfo.userid,
      status: orderState,
      page: page,
      pageSize: 10,
      type: GlobalStore.store.getState().userInfo.isCustomer ? '6' : '1,7,8',
    );
    if (res.success) {
      List list = res.data['data'];
      List items = list.map((e) => FixListItemModel.fromJson(e)).toList();
      ctx.dispatch(EngineerListViewActionCreator.onGetData(items, page));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
      ctx.dispatch(EngineerListViewActionCreator.onGetData([], page));
    }
    return;
  }
  int orderState = ctx.state.currentSortIndex + 1;
  if (ctx.state.currentSortIndex == 2) orderState = 4;
  if (ctx.state.currentSortIndex == 3) orderState = 5;
  ResultData res = await CommonNetWork.fixOrderList(
    workId: GlobalStore.store.getState().userInfo.userid,
    status: orderState,
    page: page,
    pageSize: 10,
  );
  ctx.state.type = 2;
  if (res.success) {
    List list = res.data['data'];
    List items = list.map((e) => FixListItemModel.fromJson(e)).toList();
    ctx.dispatch(EngineerListViewActionCreator.onGetData(items, page));
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
    ctx.dispatch(EngineerListViewActionCreator.onGetData([], page));
  }
}
